package com.fs.base.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fs.base.param.SysConstant;
import com.fs.base.pojo.User;
import com.fs.base.pojo.UserRole;
import com.fs.base.repository.RoleRepository;
import com.fs.base.repository.UserRepository;
import com.fs.base.service.RoleService;
import com.fs.base.utils.ApplicationUtils;
import com.fs.base.utils.Md5Utils;
import com.fs.base.vo.JsonResponse;
import com.fs.base.vo.SysPath;

/**
 * 
 * @author DeveloperKK
 *
 */
@Controller
@RequestMapping("/console/user/rewrite")
public class UserController {
   private static final Logger log = Logger.getLogger(UserController.class); 
   @Autowired private UserRepository userRepository;
   @Autowired private RoleRepository roleRepository;
   @Autowired private RoleService roleService;
   
   
    
    @GetMapping("{modleName}/view")
	public String view(@PathVariable String modleName, HttpServletRequest req) {
		return SysPath.BACK_PATH.concat("/"+modleName).concat("/view");
	}
    
    @ResponseBody
	@RequestMapping("updateUserStatus")
	public JsonResponse updateUserStatus(HttpServletRequest request){
    	try {
            String id = request.getParameter("id");
            String status = request.getParameter("status");
            User user = userRepository.findOne(id);
            user.setStatus(Integer.parseInt(status));
            userRepository.save(user);
            return JsonResponse.success();
		}catch (Exception e){
    		e.printStackTrace();
    		log.error(e.getMessage());
    		return JsonResponse.error(e.getMessage());
		}
	}


    /**
     * 修改密码跳转页面
     * @param req
     * @return
     */
    @RequestMapping("/update")
   	public String update(HttpServletRequest req) {
   		return SysPath.BACK_PATH.concat("/user").concat("/updatePwd");
   	}
    
    /**
     * 重置账号密码 重置后的账号密码与账号相同
     * @param req
     * @return
     */
    @ResponseBody
	@RequestMapping("/resetPwd")
	public JsonResponse resetPwd(HttpServletRequest req) {
		try {
			User user = (User) ApplicationUtils.requestData2Bean(User.class,true);
			if(user!=null){
				//重置后的密码为当前账号
				String newPwd = Md5Utils.md5(user.getAccount());
				userRepository.updatePwdById(newPwd, user.getId());
				return JsonResponse.success();
			}else{
				return JsonResponse.error("未选中记录!");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
    
    /**
     * 修改账号密码
     * @param req
     * @return
     */
    @ResponseBody
	@RequestMapping("/updatePwd")
	public JsonResponse updatePwd(HttpServletRequest req) {
    	try {
			User user = ApplicationUtils.User();
			String p = req.getParameter("oldPwd");
			String oldPwd = Md5Utils.md5(p);
			if(user.getPwd().equals(oldPwd)){
				String newPwd = req.getParameter("pwd");
				userRepository.updatePwdById(Md5Utils.md5(newPwd),user.getId());
				return JsonResponse.success();
			}else{
				return JsonResponse.error("原密码输入错误!");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
    
    /**
     * 用户新增
     * @param req
     * @return
     */
    @ResponseBody
	@RequestMapping("{model}/add")
	public JsonResponse add(@PathVariable String model,HttpServletRequest req) {
    	try {
			User user = (User)ApplicationUtils.requestData2Bean(User.class, true);
			String pwd = user.getPwd();
			if(pwd!=null){
				user.setPwd(Md5Utils.md5(pwd));
			}
			user = userRepository.save(user);
			//非用户管理模块新增时默认配置角色：SM_ROLE
			if(!model.equals("user")){
				String userId = user.getId();
				String roleId = roleRepository.findByRoleName(SysConstant.SMS_ROLE).getId();
				List<UserRole> list = new ArrayList<UserRole>();
				list.add(new UserRole(userId,roleId));
				//配置默认的权限
				roleService.configUserRole(userId, list);
			}
			return JsonResponse.success();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
    
    
    @ResponseBody
   	@RequestMapping("/modify")
   	public JsonResponse modify(HttpServletRequest req) {
       	try {
       		Map<String, Object> map = ApplicationUtils.getRequestDatas();
       		String userId = (String) map.get("id");
       		/*String pwd = (String) map.get("pwd");
			if(pwd!=null){
				map.put("pwd", Md5Utils.md5(pwd.toString()));
			}*/
			User oldUser = userRepository.findOne(userId);
   			User user = modify(map, oldUser );
   			
   			userRepository.save(user);
   			return JsonResponse.success();
   		} catch (Exception e) {
   			log.error(e.getMessage());
   			e.printStackTrace();
   			return JsonResponse.error(e.getMessage());
   		}
   	}
    
    
    /**
     * 信息配置
     * @return
     */
	/*@ResponseBody
	@RequestMapping("/config")
	public JsonResponse config() {
		try {
			Map<String, Object> map = ApplicationUtils.getRequestDatas();
			String userId = (String) map.get("userId");
			User cu = userRepository.findOne(userId);//判断是否是有效的userId
			if(cu!=null){
				map.remove("companyNumber");
				map.remove("createrId");
				map.remove("userId");
				User c = modify(map, cu);
				c.setSmsSignature(StringTools.forMatSign(c.getSmsSignature()));
				userRepository.save(c);
			}else{//新增
				User user = (User) ApplicationUtils.requestData2Bean(User.class,true);
				//String userId = customer.getId();
				user.setSmsSignature(StringTools.forMatSign(user.getSmsSignature()));
				customer = customerRepository.save(customer);
				String cId = customer.getId();
				User user = userRepository.findOne(userId);
				user.setCustomerId(cId);
				userRepository.save(user);
				userRepository.save(user);
				//Customer cus = ApplicationUtils.sessionCustomer();
				User cus = ApplicationUtils.User();
				if(cus!=null){
					Combo combo = ucs.getComboByUserId(cus.getId());
					UserCombo cc = ucs.getUserCombobyUserId(cus.getId());
					if(combo!=null){
						//cc = ccs.joinEntity(combo.getId(),cId,combo.getComboStatus(),userId);
						//cc = ccs.joinEntity(combo.getId(),customer.getId(),combo.getComboStatus(),customer.getId());
						ucs.save(cc);
					}else if(cc!=null){
						//父级账户的套餐共享给子账户
						//cc = ccs.joinEntity(cc.getComboId(),cId,cc.getStatus(),userId);
						//cc = ccs.joinEntity(cc.getComboId(),customer.getId(),cc.getStatus(),customer.getId());
						ucs.save(cc);
					}
				}
			}
			return JsonResponse.success();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}*/
	/**
	 * 修改企业状态
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateStatus")
	public JsonResponse updateStatus(HttpServletRequest req) {
		try {
			String id = req.getParameter("id");
			String status = req.getParameter("status");
			userRepository.updateStatus(status, id);
			return JsonResponse.success();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
	
	private User modify(Map<String, Object> map,User cus){
		String oldJson = JSON.toJSONString(cus);
		@SuppressWarnings("unchecked")
		Map<String, Object> oldMap = JSON.parseObject(oldJson, Map.class);
		oldMap.putAll(map);
		String json = JSON.toJSONString(oldMap) ;
		User user = JSON.parseObject(json, cus.getClass());
		return user;
	}
}
